﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using Microsoft.Practices.Mobile.ContainerModel;

namespace EditUsers_Best
{
    internal class TaskService : ITaskService
    {
        Container container;

        public TaskService(Container container)
        {
            // Save the container passed in (this will nearly always 
            // be the root container for the app)
            this.container = container;
            this.Tasks = new Dictionary<string, TaskDetail>();
        }

        #region ITaskService Members

        public Dictionary<string, TaskDetail> Tasks { get; private set; }

        public void Register<TView>(string taskName, Icon icon) where TView : IView
        {
            // Store as a named task an icon and a delegate instance that 
            // will be used (at some point)to call the View.
            TaskDetail taskDetail = 
                new TaskDetail { 
                    Icon = icon, 
                    Action = (c) => c.Resolve<TView>().ShowDialog()
                };
            Tasks.Add(taskName, taskDetail);
        }

        /// <summary>
        /// The Execute function is called by clients of the Task Service (the shell presenter)
        /// when we want to instantiate types associated with a module and get them running.
        /// </summary>
        /// <param name="taskName"></param>
        public void Execute(string taskName)
        {
			if (!Tasks.ContainsKey(taskName))
				return;

            // Create a child DI container just for this module, and then
            // execute the action function for the IView
            using (var child = container.CreateChildContainer())
            {
                Tasks[taskName].Action.Invoke(child);
            }
        }

        #endregion
    }
}
